//
//  JCLStatusPictureView.swift
//  WeiBo
//
//  Created by DDC on 2017/9/18.
//  Copyright © 2017年 DDC. All rights reserved.
//

import UIKit

class JCLStatusPictureView: UIView {
    
    var viewModel:JCLStatusViewModel? {
        didSet {
            
            calcViewSize()
        }
    }
    
    func calcViewSize () {
        
        // 单图设置大小
        if viewModel?.picURLs?.count == 1 {
        
            let viewSize = viewModel?.pictureSize ?? CGSize()
            let v = subviews[0]
            
            v.frame = CGRect(x: 0, y: 0, width: viewSize.width, height: viewSize.height - jclPictureOuterMargin)
    
        }else {
            
            // 多图恢复第一个图片的大小
            let v = subviews[0]
            
            v.frame = CGRect(x: 0, y: 0, width: jclPictureItemWidth, height: jclPictureItemWidth)
            
        }
        // 修改高度约束
        pictureHeightCons.constant = viewModel?.pictureSize.height ?? 0
    }
    /// 设置数据
    var urls:[JCLStatusPicture]? {
        didSet {
            
            /// 遍历子视图，全部隐藏
            for v in subviews {
                v.isHidden = true
            }
            /// 循环创建视图显示
            var index = 0
            for url in urls ?? [] {
                
                let iv = subviews[index] as! UIImageView
                
                /// 4张图片的时候 跳过第三张，显示田字样式布局
                if index == 1 && urls?.count == 4 {
                    
                    index += 1
                }
                
                iv.jcl_setImageView(urlString: url.thumbnail_pic)
                
                /// 设置gif扩展名显示图片
                iv.subviews[0].isHidden = (((url.thumbnail_pic ?? "") as NSString).pathExtension.lowercased() != "gif" )
                
                iv.isHidden = false
                
                /// 显示样式
                iv.contentMode = .scaleAspectFill
                iv.clipsToBounds = true
                
                index += 1
                
            }
            
            
        }
    }
    

    @IBOutlet weak var pictureHeightCons:NSLayoutConstraint!
    
    override func awakeFromNib() {
        
        setUpUI()
    }
    
    /// @param selectedIndex    选中照片索引
    /// @param urls             浏览照片 URL 字符串数组
    /// @param parentImageViews 父视图的图像视图数组，用户展现和解除转场动画参照
    
    @objc func tapImageViewClick (tap:UITapGestureRecognizer) {
        
        guard let iv = tap.view ,
              let URLs = viewModel?.picURLs
        else {
            return
        }
        /// 选中照片索引
        var  selectedIndex = iv.tag
        /// 4张图片的逻辑
        if URLs.count == 4 && selectedIndex > 1 {
           selectedIndex -= 1
        }
        /// 浏览照片 URL 字符串
        let urls = (URLs as NSArray).value(forKey: "largePicString") as! [String]
        /// 父视图的图像视图数组
        var imageViewList = [UIImageView]()
        
        /// 遍历
        for iv in subviews as! [UIImageView] {
            
            if !iv.isHidden {
                imageViewList.append(iv)
            }
            
        }
        /// 发送通知
        NotificationCenter.default.post(
            name: NSNotification.Name(rawValue: JCLStatusCellBrowserPhotoNotification),
            object: self,
            userInfo: [
                 JCLStatusURLsNotificationKey:urls,
                 JCLStatusImageViewsNotificationKey:imageViewList,
                 JCLStatusSelectedIndexNotificationKey:selectedIndex
                    ])
    }

}
// MARK: - 设置配图视图布局
extension JCLStatusPictureView {
    
    fileprivate func setUpUI () {
        
        /// 超出边界切除
        clipsToBounds = true
        
        let count = 9
        
        for i in 0..<count {
            
            let iv = UIImageView()
            /// 背景颜色
            iv.backgroundColor = UIColor.white
            
            let rect = CGRect(x: 0, y: jclPictureInterMargin, width: jclPictureItemWidth, height: jclPictureItemWidth)
            
            /// 列数
            let col = CGFloat(i % 3)
            /// 行数
            let row = CGFloat(i / 3)
            
            let offsetX = col * (jclPictureItemWidth + jclPictureInterMargin)
            let offsetY = row * (jclPictureInterMargin + jclPictureItemWidth)
            iv.frame = rect.offsetBy(dx: offsetX, dy: offsetY )
            
            addSubview(iv)
            // 打开iv的交互
            iv.isUserInteractionEnabled = true 
            
            // 为图片添加点击手势
            let tap = UITapGestureRecognizer(target: self, action: #selector(tapImageViewClick))
            
            iv.addGestureRecognizer(tap)
            
            // 设置imageView的tag值
            iv.tag = i
            gifImageIcon(iv: iv)
        }
        
    }
    
    fileprivate func gifImageIcon(iv:UIImageView){
        // 添加gif图标
        let gifImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
        iv.addSubview(gifImageView)
        // 关闭自动左上角对齐
        gifImageView.translatesAutoresizingMaskIntoConstraints = false
        // 设置自动布局到右下角
        iv.addConstraint(NSLayoutConstraint(item: gifImageView, attribute: .right, relatedBy: .equal, toItem: iv, attribute: .right, multiplier: 1.0, constant: 0))
        iv.addConstraint(NSLayoutConstraint(item: gifImageView, attribute: .bottom, relatedBy: .equal, toItem: iv, attribute: .bottom, multiplier: 1.0, constant: 0))
    }
}

